package com.qdxwx.web.controller.ajax;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.models.category.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/ajax/category")
public class AjaxCategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list.json")
    @ResponseBody
    public AjaxResult list(HttpServletRequest request){
        Integer channelId = TKConvert.toInteger(request.getParameter("channelId"),null);
        Integer subjectId = TKConvert.toInteger(request.getParameter("subjectId"),null);
        Integer parentId = TKConvert.toInteger(request.getParameter("parentId"),0);
        Category category = new Category();
        category.setChannelId(channelId);
        category.setSubjectId(subjectId);
        category.setParentId(parentId);
        category.setStatus(0);
        List<Category> list = categoryService.getList(category);
        return AjaxResult.success(list);
    }

    /**
     * 获取树形菜单json数据
     */
    @RequestMapping(value = "/ztree.json", method = RequestMethod.GET)
    @ResponseBody
    public Object Ztree() {
        Category category = new Category();
        category.setChannelId(11);
        category.setParentId(0);
        List<Category> list = categoryService.getList(category);
        List<HashMap<String, Object>> result = new ArrayList<>();
        return Splicing(list, result);
    }

    /**
     * 拼接树形菜单所需要的json格式
     */
    private Object Splicing(List<Category> categorys, List<HashMap<String, Object>> result) {
        for (Category category : categorys) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", category.getCategoryId());
            map.put("name", category.getCategoryName());
            map.put("open", true);//展开
            List<HashMap<String, Object>> result1 = new ArrayList<>();
            List<Category> children = categoryService.getChildren(category.getCategoryId());
            if(children == null) children = new ArrayList<>();
            map.put("children", Splicing(children, result1));
            result.add(map);
        }
        return result;
    }
}
